package com.fen.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fen.common.Result;
import com.fen.pojo.User;
import com.fen.service.UserServict;
import com.fen.utils.FormatUtils;
import com.fen.utils.Md5Utils;
import com.fen.vo.requset.RequsetLogonov;
import com.fen.vo.requset.RequsetUserov;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import lombok.extern.log4j.Log4j2;
import org.apache.catalina.session.StandardSession;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
* @Description: userController
* @Author: lijiafen
* @Date:  2021/10/29
* @Time: 21:05
* @eamil: 2368044269@qq.com
*/
@Log4j2
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserServict userServict;

    @Autowired
    private Producer producer;
    /**
    * @Description: 注册接口
    * @Author: lijiafen
    * @Date:  2021/10/30
    * @Time: 20:33
    * @eamil: 2368044269@qq.com
    */
    @PostMapping("/adduser")
    public Result register(@RequestBody RequsetUserov userov)
    {
        System.out.println(userov);
        /** 
        * @Description: 判断电话号码格式是否正确
        * @Author: lijiafen
        * @Date:  2021/10/30
        * @Time: 13:08
        * @eamil: 2368044269@qq.com
        */ 
        if (!FormatUtils.isMobile(userov.getTelephone())) {
            return com.fen.common.Result.getFailure().setMsg("手机号格式错误");
        }
       /** 
       * @Description: 判断电话号码是不是已经被注册 
       * @Author: lijiafen
       * @Date:  2021/10/30
       * @Time: 13:08
       * @eamil: 2368044269@qq.com
       */  
        User user= userServict.SelectuserByphone(userov.getTelephone());
    if (StringUtils.checkValNotNull(user))
    {
        return Result.getFailure().setMsg("电话号码已经被注册");
    }
    if (userServict.adduser(userov)) {
        return Result.getSuccess().setMsg("注册成功");
    }else {
        return Result.getFailure().setMsg("注册失败");
    }
    }
/**
* @Description: 验证码图片
* @Author: lijiafen
* @Date:  2021/10/30
* @Time: 20:33
* @eamil: 2368044269@qq.com
*/
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
        response.setHeader("Cache-Control","no-store,no-cache");
        response.setContentType("image/jpeg");
        //验证码内容
        String text = producer.createText();
        //得到验证码图片
        BufferedImage image = producer.createImage(text);
        HttpSession httpSession=request.getSession();
      /*   ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(Constants.KAPTCHA_SESSION_KEY,text);
        redisTemplate.expire(Constants.KAPTCHA_SESSION_KEY,60*1000, TimeUnit.MILLISECONDS
      httpSession.setAttribute(Constants.KAPTCHA_SESSION_KEY,text);
        //设置过期时间60s*/
        HttpSession session = request.getSession();
        session.setAttribute(Constants.KAPTCHA_BORDER_THICKNESS,text);
       session.setMaxInactiveInterval(60);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image,"jpg",out);
        IOUtils.closeQuietly(out);
    }
    /*查询所有用户*/
    @GetMapping("/user")
    public Result selectuser()
    {
        List<User> list = userServict.list();
        return Result.getSuccess().setDate(list);
    }
/**
* @Description: 用户登陆方法
* @Author: lijiafen
* @Date:  2021/10/30
* @Time: 20:33
* @eamil: 2368044269@qq.com
*/
     @PostMapping("/login")
    public Result login(HttpServletRequest request,@RequestBody RequsetLogonov requsetLogonov)
    {
        /*System.out.println(requsetLogonov);
       HttpSession session=request.getSession();
        String attribute = (String) session.getAttribute(Constants.KAPTCHA_BORDER_THICKNESS);
       if (attribute.equalsIgnoreCase(requsetLogonov.getCheckcode())){
          return Result.getFailure().setMsg("验证码错误");
       }*/
        User user=userServict.SelectuserByphone(requsetLogonov.getTelephone());
        if (user==null)
        {
        return Result.getFailure().setMsg("用户名错误");
        }
        if (!(user.getPassword().equals(Md5Utils.hash(requsetLogonov.getPassword())))) {
            return Result.getFailure().setMsg("密码错误");
        }
        Map<String,Object>map =new HashMap<>();
        if (user.getType() ==1)
        {
            map.put("isAdmin",true);
            System.out.println("欢迎"+user.getUsername()+"先生");
            return Result.getSuccess().setDate(map).setMsg("登陆成功");
        }else {
            map.put("isAdmin",false);
            System.out.println("欢迎"+user.getUsername()+"先生");
            return Result.getSuccess().setDate(map).setMsg("登陆成功");
        }
    }
    /**
    * @Description: 修改密码方法
    * @Author: lijiafen
    * @Date:  2021/11/2
    * @Time: 17:01
    * @eamil: 2368044269@qq.com
    */
    @RequestMapping("/update")
    public Result updatepassword(String password1,String password,Integer id)
    {
        System.out.println(password);
        User user = userServict.getById(id);
        if (!(user.getPassword().equals(Md5Utils.hash(password))))
        {
            return Result.getFailure().setMsg("原密码错误");
        }
        password1=Md5Utils.hash(password1);
        user.setPassword(password1);
        if (userServict.saveOrUpdate(user))
        {
            System.out.println(user.getPassword());
           return Result.getSuccess().setMsg("密码修改成功");
        }
        System.out.println(user.getPassword());
        return Result.getFailure().setMsg("修改失败");
    }
    /*更据姓名查询用户*/
      @RequestMapping("/userByname")
     public Result selectuserByname(String name)
     {
         User user = userServict.SelectuserByname(name);
        return Result.getSuccess().setDate(user);
     }
}